package question_answer

import (
	"fmt"
	questionAnswerDto "news_for_deepseek_interface/dto/admin/question_answer"
	"news_for_deepseek_interface/model"
	"strings"
)

func List(params questionAnswerDto.ListRequest) (response questionAnswerDto.ListResponse, err error) {
	db := model.GetInstance().GetDB()
	where := map[string]interface{}{}
	if params.Question != nil {
		where["question"] = "%" + *params.Question + "%"
	}

	if params.Answer != nil {
		where["answer"] = "%" + *params.Answer + "%"
	}

	if params.TypeClassifyId != nil {
		where["type_classify_id"] = *params.TypeClassifyId
	}

	if params.BusinessClassifyId != nil {
		where["business_classify_id"] = *params.BusinessClassifyId
	}

	if params.GenerationCount != nil {
		generationCount := strings.Split(*params.GenerationCount, "-")
		where["generation_count"] = []interface{}{generationCount[0], generationCount[1]}
	}

	// 获取总数
	var total int64
	if err = db.Model(&model.QuestionAnswerModel{}).Where(where).Count(&total).Error; err != nil {
		err = fmt.Errorf("数量查询失败%s", err.Error())
		return
	}

	// 分页查询
	offset := (params.Page - 1) * params.Limit
	var data []model.QuestionAnswerModel
	if err = db.Model(&model.QuestionAnswerModel{}).
		Where(where).
		Offset(offset).
		Limit(params.Limit).
		Order("created_at DESC,id desc").
		Find(&data).Error; err != nil {
		err = fmt.Errorf("数据查询失败%s", err.Error())
		return
	}

	// 构建响应
	response = questionAnswerDto.ListResponse{
		List:  make([]questionAnswerDto.QuestionAnswer, 0),
		Total: total,
		Page:  params.Page,
		Limit: params.Limit,
	}

	for _, v := range data {

		response.List = append(response.List, questionAnswerDto.QuestionAnswer{
			Id:                    v.Id,
			Question:              v.Question,
			Answer:                v.Answer,
			TypeClassifyId:        v.TypeClassifyId,
			TypeClassifyTitle:     model.ClassifyModel{}.GetClassifyTitle(v.TypeClassifyId),
			BusinessClassifyId:    v.BusinessClassifyId,
			BusinessClassifyTitle: model.ClassifyModel{}.GetClassifyTitle(v.BusinessClassifyId),
			CreatedAt:             v.CreatedAt.Format("2006-01-02 15:04"),
			GenerationCount:       v.GenerationCount,
		})
	}

	return
}
